home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C & C++ Multimedia Cyber Classroom
/
C and C++ Multimedia Cyber Classroom (Prentice Hall) (1998).iso
/
cpphtp2
/
code.jar
/
code
/
ch07
/
fig07_05.txt
< prev
next >
Wrap
Text File
|
1998-02-27
|
935b
|
33 lines
1 // Fig. 7.5: fig07_05.cpp
2 // Friends can access private members of a class.
3 #include <iostream.h>
4
5 // Modified Count class
6 class Count {
7 friend void setX( Count &, int ); // friend declaration
8 public:
9 Count() { x = 0; } // constructor
10 void print() const { cout << x << endl; } // output
11 private:
12 int x; // data member
13 };
14
15 // Can modify private data of Count because
16 // setX is declared as a friend function of Count
17 void setX( Count &c, int val )
18 {
19 c.x = val; // legal: setX is a friend of Count
20 }
21
22 int main()
23 {
24 Count counter;
25
26 cout << "counter.x after instantiation: ";
27 counter.print();
28 cout << "counter.x after call to setX friend function: ";
29 setX( counter, 8 ); // set x with a friend
30 counter.print();
31 return 0;
32 }